<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <form action="" id="form">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="text" name="sex">
    <button>提交</button>
  </form>

</body>

<script>

  let oForm = document.querySelector(`#form`)
  let oName = document.querySelector(`#form input[name=name]`)
  let oAge = document.querySelector(`#form input[name=age]`)
  let oSex = document.querySelector(`#form input[name=sex]`)

  // let obj = {name :`alx`,age:18}

  // let {name,age} = obj

  // console.log(name);
  // console.log(age);

  // let arr =[]

  //Ajax
  oForm.onsubmit = function (e) {

    let oNameValue = oName.value
    let oAgeValue = oAge.value
    let oSexValue = oSex.value


    let xhr = new XMLHttpRequest()

    xhr.open('post', "/add", true)

    // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    // xhr.send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`);
    // xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")

    xhr.send(JSON.stringify({
      name: oNameValue,
      age: oAgeValue,
      sex: oSexValue
    }))

    xhr.onreadystatechange = function () {

      if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {

        console.log(xhr.responseText);
      }
    }

    return false
  }


</script>

</html>